package com.frinder.demo9;

import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.persistence.SnapshotOffer;
import akka.persistence.UntypedPersistentActor;

import java.util.Arrays;
import java.util.UUID;

/**
 * Created by frinder on 2017/7/25.
 */
public class ExamplePersistentActor extends UntypedPersistentActor {

    LoggingAdapter logger = Logging.getLogger(getContext().system(), this);

    private ExampleState state = new ExampleState();

    public int getNumEvents() {
        return state.size();
    }

    @Override
    public void onReceiveRecover(Object o) throws Throwable {
        logger.info("{}.onReceiveRecover {}", getClass().getName(), o);
        if (o instanceof Evt) {
            logger.info("onReceiveRecover -- msg instanceof Event");
            logger.info("event -- {}", ((Evt) o).getData());
            state.update((Evt) o);
        } else if (o instanceof SnapshotOffer) {
            logger.info("onReceiveRecover -- msg instanceof SnapshotOffer");
            state = (ExampleState) ((SnapshotOffer) o).snapshot();
        } else {
            unhandled(o);
        }
    }

    @Override
    public void onReceiveCommand(Object o) throws Throwable {
        logger.info("{}.onReceiveCommand {}", getClass().getName(), o);
        if (o instanceof Cmd) {
            final String data = ((Cmd) o).getData();
            final Evt evt1 = new Evt(data + "-" + getNumEvents(), UUID.randomUUID().toString());
            final Evt evt2 = new Evt(data + "-" + (getNumEvents() + 1), UUID.randomUUID().toString());

            persistAll(Arrays.asList(evt1, evt2), evt -> {
                state.update(evt);
                if (evt.equals(evt2)) {
                    getContext().system().eventStream().publish(evt);
                }
            });
        } else if ("snap".equals(o)) {
            saveSnapshot(state.copy());
        } else if ("print".equals(o)) {
            logger.info("state : {}", state);
        } else {
            unhandled(o);
        }
    }

    @Override
    public String persistenceId() {
        return "sample-id-1";
    }
}
